package com.bookcode;
import com.bookcode.entity.Customer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@SpringBootApplication
public class DemoApplication implements CommandLineRunner{
    private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);    }
    @Autowired                         //注解@Autowired完成自动装配的工作
            JdbcTemplate  jdbcTemplate;            //对数据库的所有操作将要借助于JdbcTemplate
    @Override
    public void run(String... strings) throws Exception {
        log.info("Creating tables");               //日志信息输出到控制台
// 创建表customers
        jdbcTemplate.execute("DROP TABLE customers IF EXISTS");
        jdbcTemplate.execute("CREATE TABLE customers(" +
                "id SERIAL, first_name VARCHAR(255), last_name VARCHAR(255))");
        // 将整个数组的数组拆分成firstName、lastName的数组
        List<Object[]> splitUpNames = Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch",
                "Josh Long").stream()
                .map(name -> name.split(" "))
                .collect(Collectors.toList());
        // 使用Java 8流以日志信息形式输出每个元组的列表到控制台
        splitUpNames.forEach(name -> log.info(String.format("Inserting customer record for %s %s",
                name[0], name[1])));
        // 使用JdbcTemplate批处理更新数据
        jdbcTemplate.batchUpdate("INSERT INTO customers(first_name, last_name) VALUES (?,?)", splitUpNames);
        log.info("Querying for customer records where first_name = 'Josh':");
//查询first_name为‘Josh’的customer信息（id, first_name, last_name）
        jdbcTemplate.query(
                "SELECT id, first_name, last_name FROM customers WHERE first_name = ?",  new Object[] { "Josh" },
                (rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name")              )
        ).forEach(customer -> log.info(customer.toString()));
    }
}
